package com.huarun.common.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-11-09
 * @Author: Lingnan
 **/
@RestController
@RequestMapping("/wx")
public class CosController {
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private COSClient cosClient;
    @Autowired
    private TC_COS_Config tc_cos_config;

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "上传图片",notes = "POST")
    public PicUploadResult upload(@RequestParam("file") MultipartFile multipartFile) throws Exception{
        return this.picUploadService.upload(multipartFile);
    }

    /**
     * IO流读取图片
     * @param key: cos key
     */
    @RequestMapping("/ioReadImg")
    public String ioReadImg(String key, HttpServletResponse response){
        ServletOutputStream out = null;
        COSObjectInputStream ips = null;
        try {
            // 指定对象所在的存储桶
            String bucketName = this.tc_cos_config.getBucketName();
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            COSObject cosObject = cosClient.getObject(getObjectRequest);
            ips = cosObject.getObjectContent();
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ips != null){
                try {
                    ips.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
